/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller.CoreServlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.BeanUltility.*;
import Model.ObjectBean.RequestBean.*;
import Model.ObjectBean.ViewBean.*;
import java.sql.ResultSet;
import Model.DataUltility.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.*;
import Controller.CoreServlet.Ultility.SSCookie_Login;
import java.util.ArrayList;

/**
 *
 * @author Tran Nguyen Anh Tu
 * Function : verify user account informations 
 * How to work :
 * 1. Receive Account Informations from client and populate to AccountInfo_FrClient
 * 2. Look for in database!
 * 3. Compare and return result for User
 */
public class LoginServlet extends HttpServlet {

    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //response.setHeader("Cache-Control", "no-cache");
               // response.setHeader("Cache-Control", "no-store");        
                //response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
                //response.setDateHeader("Expires", 0); // Proxies.
        
           
            request.setCharacterEncoding("UTF-8");
            
            response.setContentType("text/html;charset=UTF-8");
            
            PrintWriter out = response.getWriter();
            
            UserAccount_FrClient clientInfo= new UserAccount_FrClient();
            
            LoginStatus status =new LoginStatus();  
            
            status.setStatus("false");
            
            PersonalInfo_FrDatabase perInfo = new PersonalInfo_FrDatabase(); 
            
            Data_Access accessDB = new Data_Access();
            
            String check=request.getParameter("cbRemember");
            if(check==null)
                check="notRemember";

                      
            RequestDispatcher dispatcher =request.getRequestDispatcher("/WEB-INF/MainJSP/LoginPage.jsp");

      try{     
            
            
            // 1 : check by value
            if(SSCookie_Login.check_cookieLoginInfo(request,1,"logged"))
            {
                status.setStatus("true");
                perInfo.setFirstname(SSCookie_Login.get_cookieInfo(request,"perInf"));
                 request.getSession().setAttribute("status", status);
                dispatcher.forward(request, response);
                out.println("Trong cookies");
            }
            else
            {
            PopulateBean.populateBeans(clientInfo,request);
            out.println(clientInfo.getPassword());
            //Step2
            String []column={"id","passw"};
            String []data={clientInfo.getUsername(),clientInfo.getPassword()};
            ResultSet rs = accessDB.getInformation("login_account", column, data);
            
            //Step2
            String []column1={"id"};
            String []data1={clientInfo.getUsername()};
            ResultSet rs1 =accessDB.getInformation("personal_info",column1,data1);
            ResultsetMapper.mapperResultsettoObject(rs1,PersonalInfo_FrDatabase.class,perInfo);
            
            //Step 3
            rs.last();
            int count=rs.getRow();
            
            //
             // If login successfully , send session cookie to browser . 
             // It will be save in browser memory and lost when browser quit.
             //
            if(count==1)
            {
                
                if(check.equals("Remember"))
                {
                 status.setStatus("true"); 
                // add cookie for this user
                SSCookie_Login.add_LongTime_Cookies(response,clientInfo.getUsername(),"logged",60*60*24*365);
                //SSCookie_Login.add_LongTime_Cookies(response,"perInf",perInfo.getFirstname(),60*60*24*365);
                SSCookie_Login.add_LongTime_Cookies(response,"username",perInfo.getId(),60*60*24*365);
                SSCookie_Login.add_LongTime_Cookies(response,"passw",clientInfo.getPassword(),60*60*24*365);
                //request.getSession().setAttribute("perInfo",perInfo); 
                request.getSession().setAttribute("status", status);
                request.getSession().setAttribute("perInfo", perInfo);
                dispatcher.forward(request, response);
                }
               else
                {
                status.setStatus("true"); 
                // add cookie for this user
                SSCookie_Login.add_ShortTime_Cookies(response,clientInfo.getUsername(),"logged");
                //SSCookie_Login.add_ShortTime_Cookies(response,"perInf",perInfo.getFirstname());
                SSCookie_Login.add_ShortTime_Cookies(response,"username",clientInfo.getUsername());
                SSCookie_Login.add_ShortTime_Cookies(response,"passw",clientInfo.getPassword());
               request.getSession().setAttribute("status", status);    
               request.getSession().setAttribute("perInfo", perInfo);
                dispatcher.forward(request, response);
               //out.println("Check thành công");
                }
            }
            else
            {  
                status.setStatus("false");
                request.getSession().setAttribute("status", status);
                dispatcher.forward(request, response);
                //out.println("check thất bại");
            }
            }
        } catch (Exception ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
            
            dispatcher.forward(request, response);
            out.println("Dính exception");
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }
    
    

    
}
